package org.hgf.testrabbitmq.consumer.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.hgf.testrabbitmq.consumer.service.IQueueService;
import org.hgf.testrabbitmq.consumer.service.IRabbitMqConsumerService;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * rabbitmq服务具体实现（生产者）
 *
 * @author 何国发
 * @version 1.0.0
 * @date 2022/9/7 15:04
 */
@Slf4j
@Service
public class RabbitMqConsumerServiceImpl implements IRabbitMqConsumerService {

    /**
     * 队列服务
     */
    @Resource
    private IQueueService queueService;

    /**
     * 消息监听容器
     */
    @Resource(name = "messageListenerContainer")
    private SimpleMessageListenerContainer listenerContainer;

    /**
     * 新增消息监听器
     *
     * @param queueName 队列名称
     * @author 何国发
     * @date 2022/9/7 17:02
     */
    @Override
    public void addNewListener(String queueName) {
        // 获取mq里全部队列的名称
        List<String> queueNameList = queueService.queueNameList();
        // 如果队列不存在则进行重试操作，重试5次抛出异常
        int count = 0;
        while (!queueNameList.contains(queueName))
        {
            queueNameList = queueService.queueNameList();
            count ++;

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= 5)
            {
                log.error("动态添加消费者监听队列失败，队列{}不存在", queueName);
                throw new RuntimeException("动态添加消费者监听队列失败，队列缺失！");
            }
        }

        // 进行动态添加监听队列
        listenerContainer.addQueueNames(queueName);
        log.info("添加成功：现有消费者监听队列【{}】", listenerContainer.getActiveConsumerCount());
    }
}
